package top.lyc829.leetcode.T56;

import java.util.*;

class Solution {
    public int[][] merge(int[][] intervals) {

        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        List<int[]> res = new ArrayList<>();

        for (int i = 0; i < intervals.length; i++) {
            int[] tmp = new int[2];

            if (res.size() == 0 || res.get(res.size() - 1)[1] < intervals[i][0]) {
                tmp[0] = intervals[i][0];
                tmp[1] = intervals[i][1];
                res.add(tmp);
            } else {
                res.get(res.size() - 1)[1] = Math.max(intervals[i][1],res.get(res.size() - 1)[1]) ;
            }
        }



        return res.toArray(new int[res.size()][]);
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        int[][] intervals = new int[][] {
                {1, 3}, {2, 6}, {8, 10}, {15, 18}
        };

        int[][] res = s.merge(intervals);

        System.out.println(Arrays.deepToString(res));

    }

}